package com.ruoyi.project.pay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.project.channel.channelAccount.domain.ChannelAccount;
import com.ruoyi.project.channel.channelAccount.service.IChannelAccountService;
import com.ruoyi.project.channel.channelAccountWb.domain.ChannelAccountWb;
import com.ruoyi.project.channel.channelAccountWb.service.IChannelAccountWbService;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.channelOrder.service.IChannelOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

public class WeiBoPayTimer {
    private static final Logger log = LoggerFactory.getLogger(WeiBoPayTimer.class);
    private IChannelOrderService channelOrderService;
    private IChannelAccountService channelAccountService;
    private IChannelAccountWbService channelAccountWbService;
    private PayServiceImpl payService;
    public WeiBoPayTimer(){
        channelOrderService = SpringContextUtil.getBean(IChannelOrderService.class);
        channelAccountService = SpringContextUtil.getBean(IChannelAccountService.class);
        channelAccountWbService = SpringContextUtil.getBean(IChannelAccountWbService.class);
        payService = SpringContextUtil.getBean(PayServiceImpl.class);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    ChannelOrder searchC = new ChannelOrder();
                    searchC.setPayType("23");
                    searchC.setOrderStatus("0");
                    List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(searchC);
                    for(int i=0;i<channelOrders.size();i++){
                        getRed(channelOrders.get(i));
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
            }
        },0,30 * 1000);
    }

    private void getRed(ChannelOrder tmpOrder){
        new Thread(){
            @Override
            public void run() {
                // 获取交易id
                String tradeId = WBRedPackageUtil.getTradeId(tmpOrder.getPayUrl());
                ChannelAccount searchAccount = new ChannelAccount();
                searchAccount.setPayType("23");
                searchAccount.setAccount(tmpOrder.getAccount());
                List<ChannelAccount> accounts =  channelAccountService.selectChannelAccountList(searchAccount);
                if(accounts.size() == 0){
                    log.error("找不到付款微博账号："+ searchAccount.toString());
                    return;
                }
                // 查询是否已经付款
                JSONObject isPayObj = WBRedPackageUtil.checkOrder(tradeId,accounts.get(0).getAppid());
                JSONObject data = isPayObj.getJSONObject("data");
                JSONArray array = data.getJSONArray("biz");
                if(array.size()==0){
                    return;
                }
                JSONObject result = array.getJSONObject(0);
                if(result.getString("status").equals("2")){
                    log.info("订单编号："+tmpOrder.getPtOrderno()+"付款成功！金额："+result.getString("amount")+";付款微博账号："+accounts.get(0).getAccount());
                    // 2 代表已经付款
                    String orderId = result.getString("order_id");
                    // 获取所有微博账号
                    ChannelAccountWb search = new ChannelAccountWb();
                    search.setOrderId(tmpOrder.getOrderId());
                    List<ChannelAccountWb> wbs = channelAccountWbService.selectChannelAccountWbList(search);
                    int sum = 0 ;
                    Double sumAccount = 0.00;
                    for(int j=0;j<wbs.size();j++){
                        ChannelAccountWb channelAccountWb = wbs.get(j);
                        searchAccount = new ChannelAccount();
                        searchAccount.setPayType("23");
                        searchAccount.setAccount(channelAccountWb.getRecAccount());
                        List<ChannelAccount> receiveAccounts =  channelAccountService.selectChannelAccountList(searchAccount);
                        if(receiveAccounts.size()==0){
                            log.error("找不到微博账号："+channelAccountWb.getRecAccount());
                            continue;
                        }
                        if(channelAccountWb.getRecStatus().equals("1")){
                            sum++;
                            sumAccount = sumAccount + Double.valueOf(channelAccountWb.getAmount()+"");
                        }else{
                            ChannelAccount recAccount = receiveAccounts.get(0);
                            JSONObject receiveObj = WBRedPackageUtil.sendRedpackage(orderId,accounts.get(0).getAppid(),recAccount.getAlias());
                            // {"code":"100000","msg":"\u64cd\u4f5c\u6210\u529f","data":{"url":"sinaweibo:\/\/browser\/close"}}
                            if(receiveObj.getString("code").equals("100000")){
                                // 通知成功 开始拆包
                                String res = WBRedPackageUtil.pickMoney(orderId, recAccount.getAppid());
                                if(res.contains("红包金额已存入您的钱包")){
                                    // 已经收到红包了
                                    sum++;
                                    channelAccountWb.setRecStatus("1");
                                    String recamount  = WBRedPackageUtil.getAmount(res);
                                    sumAccount = sumAccount + Double.valueOf(recamount);
                                    channelAccountWb.setAmount(BigDecimal.valueOf(Double.valueOf(recamount)));
                                    channelAccountWb.setUpdateTime(new Date());
                                    channelAccountWbService.updateChannelAccountWb(channelAccountWb);

                                }
                            }
                        }
                        if(sum==wbs.size()){
//                        if(sum==wbs.size() && tmpOrder.getAmount().compareTo(BigDecimal.valueOf(sumAccount)) == 0){
                            tmpOrder.setPayAmount(BigDecimal.valueOf(Double.valueOf(sumAccount)));
                            tmpOrder.setOrderId(tmpOrder.getPtOrderno());
                            payService.updateOrder(tmpOrder);
                        }
                    }
                }
            }
        }.start();
    }
}
